<template>
  <div class="app-container">
    <el-card class="filter-container">
      <div class="filter-item">
        <el-form :inline="true" :model="queryParams" size="small">
          <el-form-item label="标题">
            <el-input v-model="queryParams.title" placeholder="请输入公文标题" clearable />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="queryParams.type" placeholder="请选择公文类型" clearable>
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择公文状态" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="list-container">
      <div class="action-container">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增公文</el-button>
      </div>

      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部公文" name="all"></el-tab-pane>
        <el-tab-pane label="我创建的" name="my"></el-tab-pane>
        <el-tab-pane label="待我审批" name="pending"></el-tab-pane>
        <el-tab-pane label="我已审批" name="approved"></el-tab-pane>
        <el-tab-pane label="抄送给我" name="cc"></el-tab-pane>
      </el-tabs>

      <el-table v-loading="loading" :data="documentList" border>
        <el-table-column label="公文编号" prop="docNumber" width="150" />
        <el-table-column label="标题" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="类型" prop="type" width="100">
          <template slot-scope="scope">
            {{ formatType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="发文单位" prop="issuer" width="150" />
        <el-table-column label="创建人" prop="creatorName" width="100" />
        <el-table-column label="创建时间" prop="createTime" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
            <el-button
              v-if="scope.row.status === 0 && scope.row.creatorId === userId"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              v-if="scope.row.status === 0 && scope.row.creatorId === userId"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-button
              v-if="scope.row.status === 0 && scope.row.creatorId === userId"
              size="mini"
              type="text"
              icon="el-icon-s-promotion"
              @click="handleSubmit(scope.row)"
            >提交</el-button>
            <el-button
              v-if="scope.row.status === 1 && scope.row.currentApproverId === userId"
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleApprove(scope.row)"
            >审批</el-button>
            <el-button
              v-if="scope.row.status === 2 && hasArchivePermission"
              size="mini"
              type="text"
              icon="el-icon-folder"
              @click="handleArchive(scope.row)"
            >归档</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.size"
        @pagination="getList"
      />
    </el-card>

    <!-- 查看公文对话框 -->
    <el-dialog :title="'查看公文：' + viewForm.title" :visible.sync="viewDialogVisible" width="70%">
      <document-detail :document="viewForm" />
    </el-dialog>

    <!-- 审批公文对话框 -->
    <el-dialog title="审批公文" :visible.sync="approveDialogVisible" width="50%">
      <el-form ref="approveForm" :model="approveForm" :rules="approveRules" label-width="100px">
        <el-form-item label="审批结果" prop="result">
          <el-radio-group v-model="approveForm.result">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见" prop="comment">
          <el-input v-model="approveForm.comment" type="textarea" rows="4" placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApprove">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDocumentPage, getMyDocumentPage, getPendingApprovalPage, getApprovedPage, getCcToMePage, deleteDocument, submitDocument, archiveDocument } from '@/api/document'
import { approveDocument } from '@/api/approval'
import Pagination from '@/components/Pagination'
import DocumentDetail from './components/DocumentDetail'
import { formatDateTime } from '@/utils/index'

export default {
  name: 'DocumentList',
  components: { Pagination, DocumentDetail },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 公文列表
      documentList: [],
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        title: undefined,
        type: undefined,
        status: undefined
      },
      // 当前选中的标签页
      activeTab: 'all',
      // 用户ID
      userId: this.$store.getters.userId,
      // 是否有归档权限
      hasArchivePermission: this.$store.getters.permissions.includes('document:archive'),
      // 公文类型选项
      typeOptions: [
        { value: 1, label: '通知' },
        { value: 2, label: '请示' },
        { value: 3, label: '报告' },
        { value: 4, label: '决定' },
        { value: 5, label: '其他' }
      ],
      // 公文状态选项
      statusOptions: [
        { value: 0, label: '草稿' },
        { value: 1, label: '审批中' },
        { value: 2, label: '已通过' },
        { value: 3, label: '已驳回' },
        { value: 4, label: '已归档' }
      ],
      // 查看对话框
      viewDialogVisible: false,
      viewForm: {},
      // 审批对话框
      approveDialogVisible: false,
      approveForm: {
        documentId: undefined,
        result: 1,
        comment: ''
      },
      approveRules: {
        result: [{ required: true, message: '请选择审批结果', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    formatDateTime,
    // 格式化公文类型
    formatType(type) {
      const typeMap = {
        1: '通知',
        2: '请示',
        3: '报告',
        4: '决定',
        5: '其他'
      }
      return typeMap[type] || '未知'
    },
    // 格式化公文状态
    formatStatus(status) {
      const statusMap = {
        0: '草稿',
        1: '审批中',
        2: '已通过',
        3: '已驳回',
        4: '已归档'
      }
      return statusMap[status] || '未知'
    },
    // 获取状态标签类型
    getStatusType(status) {
      const statusTypeMap = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'danger',
        4: 'primary'
      }
      return statusTypeMap[status] || ''
    },
    // 获取公文列表
    getList() {
      this.loading = true
      let fetchMethod = getDocumentPage

      // 根据当前标签页选择不同的接口
      switch (this.activeTab) {
        case 'my':
          fetchMethod = getMyDocumentPage
          this.queryParams.userId = this.userId
          break
        case 'pending':
          fetchMethod = getPendingApprovalPage
          this.queryParams.userId = this.userId
          break
        case 'approved':
          fetchMethod = getApprovedPage
          this.queryParams.userId = this.userId
          break
        case 'cc':
          fetchMethod = getCcToMePage
          this.queryParams.userId = this.userId
          break
        default:
          fetchMethod = getDocumentPage
          delete this.queryParams.userId
      }

      fetchMethod(this.queryParams).then(response => {
        this.documentList = response.data.records
        this.total = response.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 查询按钮
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        title: undefined,
        type: undefined,
        status: undefined
      }
      this.handleQuery()
    },
    // 标签页切换
    handleTabClick() {
      this.resetQuery()
    },
    // 新增按钮
    handleAdd() {
      this.$router.push('/document/create')
    },
    // 查看按钮
    handleView(row) {
      this.viewForm = row
      this.viewDialogVisible = true
    },
    // 编辑按钮
    handleEdit(row) {
      this.$router.push(`/document/edit/${row.id}`)
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm('确认删除该公文吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDocument(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // 提交按钮
    handleSubmit(row) {
      this.$confirm('确认提交该公文进行审批吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        submitDocument(row.id).then(() => {
          this.$message.success('提交成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // 审批按钮
    handleApprove(row) {
      this.approveForm = {
        documentId: row.id,
        result: 1,
        comment: ''
      }
      this.approveDialogVisible = true
    },
    // 提交审批
    submitApprove() {
      this.$refs.approveForm.validate(valid => {
        if (valid) {
          approveDocument(this.approveForm, this.userId, this.$store.getters.name).then(() => {
            this.$message.success('审批成功')
            this.approveDialogVisible = false
            this.getList()
          })
        }
      })
    },
    // 归档按钮
    handleArchive(row) {
      this.$confirm('确认归档该公文吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        archiveDocument(row.id).then(() => {
          this.$message.success('归档成功')
          this.getList()
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.action-container {
  margin-bottom: 20px;
}
</style> 